<template><!--  @close="onclose" -->
  <el-dialog :title="title" :visible="showDialog" @close="onclose">
    <el-form ref="deptFormRef" label-width="110px" :model="deptForm" :rules="deptFormRules">
      <el-form-item label="部门名称：" prop="name">
        <el-input v-model="deptForm.name" placeholder="2-10个字符" size="medium" />
      </el-form-item>
      <el-form-item label="部门编码：" prop="code">
        <el-input v-model="deptForm.code" placeholder="2-10个字符" size="medium" />
      </el-form-item>
      <el-form-item label="部门负责人：" prop="managerId">
        <el-select v-model="deptForm.managerId" placeholder="2-10个字符" size="medium" @focus="onFocus">
          <!-- label: 指定页面看到的内容[给用户用的] 和 value：就是数据里面指定的 value 属性[给后端用] -->
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍：" prop="introduce">
        <el-input
          v-model="deptForm.introduce"
          placeholder="2-10个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>

    <!-- 具名为 footer 的插槽 -->
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="submit">确定</el-button>
        <el-button size="small" @click="onclose">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { getDepartmentById, getDepartments, getUserSimple, postDepartment, putDepartment } from '@/api/user'
export default {
  name: 'DeptDialog',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    pid: {
      type: Number,
      default: 0
    }
  },

  data() {
    const opname = async(rulse, val, callback) => {
      let res = await getDepartments()
      // 自定义校验规则的时候，要区分环境
      // 编辑状态下：需要对当前编辑的人先去排除掉
      if (this.deptForm.id) {
        res = res.filter(item => item.id !== this.pid)
      }

      switch (rulse.field) {
        case 'name':
          if (res.map(item => item.name).some(item => item === val.trim())) {
            callback(new Error(`已有${val}部门，不得重复`))
          } else {
            callback()
          }
          break
        case 'code':
          if (res.map(item => item.code).some(item => item === val.trim())) {
            callback(new Error(`已有${val}部门编码，不得重复`))
          } else {
            console.log('触发了')
            callback()
          }
          break
      }
    }
    return {

      options: [],
      value: '',
      deptForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        managerId: '', // 部门负责人id
        introduce: '', // 部门介绍
        pid: 0 // 父级部门的id
      },
      deptFormRules: {
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码的长度为2-10个字符', trigger: 'blur' },
          { validator: opname, trigger: 'blur' }
        ], // 部门编码
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' }, {
          min: 1, max: 100, message: '部门介绍的长度为1-100个字符', trigger: 'blur'
        }], // 部门介绍
        managerId: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }], // 部门负责人id
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称的长度为2-10个字符', trigger: 'blur' },
          { validator: opname, trigger: 'blur' }
        ] // 部门名称
        // pid: '' // 父级部门的id 不需要做校验
      }
    }
  },
  computed: {
    title() {
      return this.deptForm.id ? '编辑部门' : '添加部门'
    }
  },
  mounted() {
    this.onFocus
  },
  methods: {
    onclose() {
      this.$emit('close')
      this.deptForm = {
        name: '', // 部门名称
        code: '', // 部门编码
        managerId: '', // 部门负责人id
        introduce: '', // 部门介绍
        pid: 0 // 父级部门的id
      }
      this.$refs.deptFormRef.resetFields()
    },
    async onFocus() {
      const res = await getUserSimple()
      this.options = res
      console.log(this.options)
    },
    async submit() {
      try {
        await this.$refs.deptFormRef.validate()

        // 这里要处理编辑和添加
        if (this.deptForm.id) {
          // 编辑
          await putDepartment(this.deptForm)
          this.$message.success('编辑成功')
        } else {
          // 对刚要添加的子部门进行父级id 做赋值
          this.deptForm.pid = this.pid
          await postDepartment(this.deptForm)
          this.$message.success('添加成功')
        }

        // 对刚要添加的子部门进行父级id 做赋值

        // 重置表单数据
        this.$refs.deptFormRef.resetFields()
        // 重置 pid
        this.$emit('update:pid', 0)
        // 手动将 deptForm 里面的 pid 属性置空
        this.deptForm.pid = 0
        this.$emit('update:show-dialog', false)
        this.$emit('update-list')
      } catch (error) {
        console.log(error)
      }
    },
    async getDetail(id) {
      const res = await getDepartmentById(id)
      // this.deptForm.id = res.id // 后期用来做状态判断的
      // this.deptForm.name = res.name
      // this.deptForm.code = res.code
      // this.deptForm.managerId = res.managerId // 给负责人赋值
      // this.deptForm.introduce = res.introduce
      // this.deptForm.pid = res.pid
      // const cloneRes = { ...res }
      // 移除对象中的属性
      delete res.createTime
      delete res.managerName
      this.deptForm = res
    }
  }
}
</script>
<style scoped>
.el-select {
    width: 100%;
}
</style>
